<template>
  <div class="search">
    <!-- 导航栏 -->
    <van-nav-bar title="搜索中心" left-arrow @click-left="$router.back()" />

    <!-- 搜索框 -->
    <van-search
      v-model.trim="key"
      shape="round"
      @input="onInput"
      show-action
      placeholder="请输入搜索关键词"
      @search="onSearch"
    >
      <template #action>
        <div @click="onSearch">搜索</div>
      </template>
    </van-search>

    <!-- 历史记录 -->
    <van-cell-group v-if="!key">
      <van-cell title="历史记录" />
      <van-cell
        v-for="(item, index) in historyList"
        :key="index"
        :title="item"
        @click="$router.push({ name: 'result', query: { key: item } })"
      />
    </van-cell-group>

    <!-- 联想词汇 -->
    <van-cell-group v-else>
      <van-cell
        v-for="(item, index) in colorSuggests"
        :key="index"
        icon="search"
        @click="
          $router.push({
            name: 'result',
            query: { key: suggestList[index] }
          })
        "
      >
        <div v-html="item"></div>
      </van-cell>
    </van-cell-group>
  </div>
</template>

<script>
import { suggestAPI } from '@/api'
export default {
  data () {
    return {
      key: '',
      suggestList: [],
      timerId: null,
      historyList: JSON.parse(window.localStorage.getItem('history')) || []
    }
  },
  methods: {
    onSearch () {
      // 本次搜索不在历史里面就要保存起来
      if (this.historyList.indexOf(this.key) === -1) {
        // 把key加到数组里面去
        this.historyList.unshift(this.key)
        // 保存到本地
        window.localStorage.setItem('history', JSON.stringify(this.historyList))
      }
      // 判断是否有值
      if (this.key) {
        this.$router.push({
          name: 'result',
          query: {
            key: this.key
          }
        })
      }
    },
    onInput () {
      // 清除定时器
      clearTimeout(this.timerId)
      this.timerId = setTimeout(async () => {
        // 拿到输入的内容，发请求获取联想词汇
        if (this.key) {
          const res = await suggestAPI({
            q: this.key
          })
          console.log(res)
          this.suggestList = res.data.data.options
        }
      }, 500)
    }
  },

  computed: {
    colorSuggests () {
      // 遍历搜索联想的数组，产生一个新数组

      const reg = new RegExp(this.key, 'ig')

      return this.suggestList.map((v) =>
        v.replace(reg, `<span style="color:red;">${this.key}</span>`)
      )
    }
  }
}
</script>

<style></style>
